package com.gears.filecover.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.csource.common.NameValuePair;
import org.csource.test.FastDFSFile;
import org.csource.test.FileManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;



public class UploadUtils {

	private static final String CONTENT_TYPE = "text/html; charset=utf-8";

	private static final String CURR_DATA_LOCATION = "CURR_DATA_LOCATION";
	private static final String CHAT_RECODE_POSITION = "CHAT_RECODE_POSITION";

	
	/**
	 * 上传文件
	 * @param myfiles
	 * @param request
	 * @param response
	 * @param writer
	 * @throws Exception
	 * @auther lk
	 * create on 2016年6月27日 下午3:53:40
	 */
	public static Map<String,Object> uploadFile(@RequestParam MultipartFile file) throws Exception {
		String result  = "";
		Map<String,Object> map = new HashMap<String, Object>();
	/*	// 初始化通用multipart解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		// 判断请求中是否有文件上传
		if (!multipartResolver.isMultipart(request)) {
			result = "上传失败";
			throw new Exception("上传失败");
		}*/

		// 解析请求，将文件信息放到迭代器里
		/*MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iter = multiRequest.getFileNames();*/
		
		// 迭代文件，存放到某一路径里
		/*while (iter.hasNext()) {
			// 取得上传文件
			MultipartFile file = multiRequest.getFile(iter.next());*/
			InputStream fis = file.getInputStream();
		      byte[] file_buff = null;
		      if (fis != null) {
		      	int len = fis.available();
		      	file_buff = new byte[len];
		      	fis.read(file_buff);
		      }

		      //Map<String,Object> map = new HashMap<String, Object>();
		      String path = new String();
		      
			if (null != file) {
				// 取得当前上传文件的文件名称
				String myFileName = file.getOriginalFilename();
				// 判断文件是否存在，文件名为空，则说明文件不
				if (myFileName.trim() != "") {

					// 重命名上传后的文件名
					String fileName = getName(myFileName);
					// 定义上传路径
//					Date now = new Date(); //获取当前时间
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化当前日期时间
				//	String dataNow = sdf.format(now);
					
					FastDFSFile fdfsfile = new FastDFSFile(fileName, file_buff, myFileName.substring(myFileName.lastIndexOf(".")+1));
					
					 path = FileManager.upload(fdfsfile);
					 
					/* map.put("fileId", fileId);
					 map.put("oldName", myFileName);
					 map.put("newName", fileName);
					 map.put("size", file.getSize());
					 map.put("dataType", dataType);
					 map.put("type", myFileName.substring(myFileName.lastIndexOf(".")+1));
					 map.put("uploadTime", dataNow);*/
					 

			/*	}*/
				return map;

			} else {
				//writer.write("上传失败");
				return null;
				//throw new Exception("上传失败");
			}
		}
		return null;
	}
	
	/**
	 * 上传文件名字变换
	 * @param myFileName
	 * @return
	 * @auther lk
	 * create on 2016年6月27日 下午3:53:06
	 */
	public static String getName(String myFileName) {
		String newName = UUID.randomUUID().toString().replaceAll("-", "") + myFileName.substring(myFileName.lastIndexOf("."));
		return newName;
	}
	
	/**
	 *   将文件转为二进制
	 */
	/*public static byte[] getFileToByte(MultipartFile file)  throws Exception{
        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
        File f = fi.getStoreLocation();
        byte[] by = null;
        try {
        	InputStream fis = new FileInputStream(f);
        	if (fis != null) {
              	int len = fis.available();
              	by = new byte[len];
              	fis.read(by);
              }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return by;
    }*/
}
